<template>
    <div>
        web3
    </div>
</template>
<script lang="ts" setup name="BlockChain">
import { onMounted, ref, Ref } from 'vue';
import Web3 from "web3";

// ABI (Application Binary Interface) 定义
const MyContractABI = [
    {
        "inputs": [],
        "stateMutability": "nonpayable",
        "type": "constructor"
    },
    {
        "inputs": [],
        "name": "getName",
        "outputs": [
            {
                "internalType": "string",
                "name": "",
                "type": "string"
            }
        ],
        "stateMutability": "view",
        "type": "function"
    },
    {
        "inputs": [
            {
                "internalType": "string",
                "name": "_newName",
                "type": "string"
            }
        ],
        "name": "setName",
        "outputs": [],
        "stateMutability": "nonpayable",
        "type": "function"
    }
    // ... 可能还有其他函数和事件
];

// 合约地址
const MY_CONTRACT_ADDRESS = '0x6d823440B90318Bc4A041E130d7A1ABfB00614Ba'; // 填充你的合约地址

// 合约实例
let myContract: Ref<any> = ref(null);

const web3Instance: Ref<any> = ref(null);

onMounted(async () => {
    const provider = new Web3.providers.HttpProvider('HTTP://127.0.0.1:7545');
    web3Instance.value = new Web3(provider);

    // 测试连接
    try {
        const accounts = await web3Instance.value.eth.getAccounts();
        const networkId = await web3Instance.value.eth.net.getId();
        console.log('Connected accounts:', accounts);
        console.log('Connected network id:', networkId); // 5777n
    } catch (error) {
        console.error('Failed to connect to Ethereum node:', error);
    }


    if (web3Instance.value) {
        myContract.value = new web3Instance.value.eth.Contract(MyContractABI, MY_CONTRACT_ADDRESS);

        // 读取合约状态或调用合约函数
        try {
            // 假设你有一个名为"getName"的getter函数
            const name = await myContract.value.methods.getName().call();
            console.log('Contract name:', name);

            // 发送交易
            // 注意: 发送交易需要签名，因此需要一个帐户的私钥，或使用Metamask等钱包
            const account = (await web3Instance.value.eth.getAccounts())[0]; // 请小心处理账户，不要在生产环境硬编码或使用不安全的方式处理私钥

            const transaction = myContract.value.methods.setName('NewName');
            const gas = await transaction.estimateGas({ from: account });
            const data = transaction.encodeABI();

            const receipt = await web3Instance.value.eth.sendTransaction({
                from: account,
                to: MY_CONTRACT_ADDRESS,
                data: data,
                gas: gas
            });

            console.log('Transaction receipt:', receipt);
        } catch (error) {
            console.error('Error interacting with contract:', error);
        }
    }
})
</script>
<style lang="scss" scoped></style>